<template>
	<div class="form-container">
		<div class="form-breadcrumb">
			<el-breadcrumb separator-class="el-icon-arrow-right">
				<el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
				<el-breadcrumb-item>活动管理</el-breadcrumb-item>
				<el-breadcrumb-item :to="{ path: '/activityPrizeList' }">活动奖品</el-breadcrumb-item>
				<el-breadcrumb-item>添加活动奖品</el-breadcrumb-item>
			</el-breadcrumb>
		</div>
		<div class="form-content">
			<el-form ref="form" :model="form" :rules="rules" label-width="126px">
				<el-form-item label="奖品名称" prop="name">
					<el-input v-model="form.name" placeholder="请输入活动奖品"></el-input>
				</el-form-item>
				<el-form-item label="子标题" prop="sub_name">
					<el-input v-model="form.sub_name" placeholder="请输入子标题"></el-input>
				</el-form-item>

				<el-form-item label="奖品编码" prop="code">
					<el-input v-model="form.code" placeholder="请输入奖品编码"></el-input>
				</el-form-item>

				<el-form-item label="奖品价值" prop="price">
					<el-input v-model="form.price" placeholder="请输入奖品价值"></el-input>
				</el-form-item>

				<el-form-item label="跳转地址">
					<el-input v-model="form.jump_addr" placeholder="请输入跳转地址"></el-input>
				</el-form-item>

				<el-form-item label="有效时间" prop="start_at">
					<el-date-picker v-model="valueTime" type="datetimerange" @change="selectTime" range-separator="至"
						start-placeholder="开始日期" end-placeholder="结束日期">
					</el-date-picker>
				</el-form-item>

				<el-form-item label="选择卖场">
					<el-select v-model="form.market_id" clearable @change="selectMarket" filterable placeholder="请选择卖场">
						<el-option v-for="item in marketList" :key="item.id" :label="item.name" :value="item.id">
						</el-option>
					</el-select>
				</el-form-item>

				<el-form-item label="状态">
					<el-radio v-model="form.status" label="1">开启</el-radio>
					<el-radio v-model="form.status" label="0">关闭</el-radio>
				</el-form-item>
				<el-form-item label="是否支持商户核销">
					<el-radio v-model="form.is_verification" label="1">支持</el-radio>
					<el-radio v-model="form.is_verification" label="0">不支持</el-radio>
				</el-form-item>
				<el-form-item label="品类限制" v-if="form.is_verification == '1'">
					<el-row>
						<el-radio v-model="form.is_cate" border size="small" label="0">全部</el-radio>
						<el-radio v-model="form.is_cate" border size="small" label="1">允许以下商品分类使用</el-radio>
					</el-row>
					<el-row>
						<el-select filterable remote reserve-keyword :remote-method="_query_cate"
							v-if="form.is_cate == '1'" v-model="cate_lst" multiple placeholder="请选择品类"
							style="width: 100%">
							<el-option v-for="item in cates" :key="item.value" :label="item.label" :value="item.value">
							</el-option>
						</el-select>
					</el-row>
				</el-form-item>
				<el-form-item label="奖品库存" prop="stock">
					<el-input v-model="form.stock" placeholder="请输入奖品库存"></el-input>
				</el-form-item>
				<el-form-item label="核销配置" prop="stock">
					<el-select v-model="form.verif_conf_status" placeholder="请选择">
						<el-option v-for="item in verifStatus" :key="item.value" :label="item.label"
							:value="item.value">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="赠送抽奖次数" prop="stock" v-if="form.verif_conf_status==1">
					<el-input v-model="form.verif_conf_data.lucky_count" placeholder="请输入赠送抽奖次数"></el-input>
				</el-form-item>
				<el-form-item label="活动方式">
					<el-radio v-model="form.ispus" label="1">购买可得</el-radio>
					<el-radio v-model="form.ispus" label="0">赠送</el-radio>
				</el-form-item>
				<el-form-item label="奖品类型">
					<el-radio-group v-model="form.type" @change="toSelectTypeFn">
						<el-radio label="0">默认（促销券）</el-radio>
						<el-radio label="1">线上优惠卷</el-radio>
						<!-- <el-radio label="2">实物</el-radio> -->
						<el-radio label="3">促销文章</el-radio>
						<el-radio label="4">直播促销券</el-radio>
						<el-radio label="5">微信红包</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item v-if="form.type != 0 && form.type != 2 && form.type != 5" :label="
            form.type == 1
              ? '选择优惠券'
              : form.type == 2
              ? '选择实物'
              : form.type == 3
              ? '选择文章'
              : form.type == 4
              ? '选择直播'
              : ''
          ">
					<span style="margin-right: 10px">{{
            form.type == "1"
              ? selectTypeOk.name
              : form.type == "3"
              ? selectTypeOk.title
              : form.type == "4"
              ? selectTypeOk.theme
              : ""
          }}</span>
					<el-button @click="selectType" size="small">点击选择</el-button>
				</el-form-item>

				<el-form-item label="奖品主图">
					<el-upload action="/api/client/base/uploadfile" list-type="picture-card"
						:on-preview="handlePictureCardPreview" ref="upload" :on-remove="handleRemove"
						:on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :auto-upload="true"
						:limit="1" :headers="myHeaders" :file-list="fileList"
						accept="image/jpeg, image/jpg, image/gif, image/png" :multiple="false">
						<i class="el-icon-plus"></i>
					</el-upload>
					<el-dialog :visible.sync="dialogVisible">
						<img width="100%" :src="dialogImageUrl" alt="" />
					</el-dialog>
				</el-form-item>

				<el-form-item label="排序">
					<el-col :span="5">
						<el-input v-model="form.sort" placeholder="数字越大越靠后"></el-input>
					</el-col>
				</el-form-item>
				<el-form-item label="活动说明">
					<VueEditor style="width: 100%" v-loading="editorLoading" element-loading-text="图片上传中"
						element-loading-background="rgba(0, 0, 0, 0.5)" useCustomImageHandler
						@image-added="handleImageAdded" :editorToolbar="customToolbar" v-model="form.remark" />
					<!-- <el-input type="textarea" v-model="form.remark" :rows="4"></el-input> -->
				</el-form-item>

				<el-form-item>
					<el-row>
						<el-button type="danger" @click="confirmAdd('form')">立即保存</el-button>
						<el-button type="default" @click="cancel()">返回</el-button>
					</el-row>
				</el-form-item>
			</el-form>
		</div>
		<!--  选择商品类型对话框 -->
		<el-dialog :title="
        form.type == '1'
          ? '选择优惠券'
          : form.type == '3'
          ? '选择促销文章'
          : form.type == '4'
          ? '选择直播'
          : ''
      " :visible.sync="dialogVisibleType" width="45%" @closed="closeFn">
			<div class="openBox">
				<div style="width: 90%">
					<div v-if="form.type == '3'" style="display: flex; justify-content: flex-end; margin-bottom: 5px">
						<el-input v-model="searchShop" placeholder="请输入文章关键词" clearable @input="clearShopFn"></el-input>
						<el-button type="primary" size="small" @click="searchShopFn">搜索</el-button>
					</div>
					<el-table border :data="typeList" style="width: 100%; margin: 20px 0">
						<el-table-column label="选择" align="center" width="50">
							<template slot-scope="scope">
								<el-radio v-model="form.rel_id" :label="
                    form.type == 4 ? scope.row.qy_living_id : scope.row.id
                  ">{{ "" }}</el-radio>
							</template>
						</el-table-column>
						<!-- <el-table-column
              prop="date"
              align="center"
              label="图片"
              width="80">
              <template slot-scope="scope">
                <img style="width:30px;height:30px;" :src="form.type=='1'?scope.row.img:form.type=='3'?scope.row.cover:''" alt="">
              </template>
            </el-table-column> -->
						<el-table-column prop="name" align="center" label="名称" width="auto">
							<template slot-scope="scope">
								<div>
									{{
                    form.type == "1"
                      ? scope.row.name
                      : form.type == "3"
                      ? scope.row.title
                      : form.type == "4"
                      ? scope.row.theme
                      : ""
                  }}
								</div>
							</template>
						</el-table-column>
						<el-table-column v-if="form.type == '4'" prop="status" align="center" label="直播状态" width="auto">
						</el-table-column>
					</el-table>
					<el-pagination @size-change="handleSizeChangeShop" @current-change="handleCurrentChangeShop"
						:current-page="typePage" :page-sizes="[5, 10, 15, 20]" :page-size="typePagesize"
						layout="total, sizes, prev, pager, next, jumper" :total="typeTotal" background>
					</el-pagination>
				</div>
				<!-- <el-radio-group v-model="form.rel_id" v-infinite-scroll="loadType">
            <el-radio :label="item.id" v-for="(item,index) in typeList" @change="selectRadio(item)" :key="index">{{form.type=='1'?item.name:form.type=='3'?item.title:''}}</el-radio>
          </el-radio-group> -->
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogVisibleType = false">取 消</el-button>
				<el-button type="primary" @click="selectSubmit">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	import {
		VueEditor
	} from "vue2-editor";
	export default {
		components: {
			VueEditor,
		},
		// name: 'Vue2Editor',
		data() {
			return {
				validate: false,
				activeName: "first",
				types: [],
				cates: [],
				form: {
					name: "",
					sub_name: "",
					img: "",
					code: "",
					price: "",
					status: "1",
					is_verification: "0",
					stock: 1,
					ispus: "0",
					type: "0",
					rel_id: "",
					sort: 100,
					remark: "",
					start_at: "",
					end_at: "",
					is_cate: "0",
					cate_lst: "",
					jump_addr: "",
					market_id: '',
					verif_conf_status: '', //核销配置开启
					verif_conf_data: {
						lucky_count: '', //赠送抽奖次数
					}, //核销配置对象
				},
				activityType: [{
					label: "抽奖",
					value: 1,
				}, ],
				cate_lst: [],

				videoUrl: "", //视频连接
				videoId: "", //视频id
				videoFlag: false,
				videoUploadPercent: 0,

				replaceList: [],

				rules: {
					name: [{
						required: true,
						message: "请输入奖品名称",
						trigger: "blur"
					}],
					code: [{
						required: true,
						message: "请输入奖品编号",
						trigger: "blur"
					}],
					sort: [{
						required: true,
						message: "请输入排序值",
						trigger: "blur"
					}],
					start_at: [{
						required: true,
						message: "请选择活动时间",
						trigger: "blur"
					}, ],
					stock: [{
						required: true,
						message: "请输入库存",
						trigger: "blur"
					}],
				},
				filter_keyword: "",
				editorLoading: false, //富文本图片loading
				customToolbar: [
					[{
						header: [false, 1, 2, 3, 4, 5, 6]
					}], //标题
					["bold", "italic", "underline", "strike"], //加粗\斜体\下划线\作废
					["blockquote", "code-block"],
					[{
							script: "sub",
						},
						{
							script: "super",
						},
					], // superscript/subscript
					[{
							indent: "-1",
						},
						{
							indent: "+1",
						},
					], // outdent/indent
					[{
						direction: "rtl",
					}, ],
					[{
						align: ""
					}, {
						align: "center"
					}, {
						align: "right"
					}], //对齐
					[{
						list: "ordered"
					}, {
						list: "bullet"
					}, {
						list: "check"
					}], //有序无序列表
					[{
						background: []
					}, {
						color: []
					}], //背景色
					["image", "link"], //图片、链接
					["clean"], //清楚格式（所谓去掉背景色这些花里胡巧）
					["code"], //代码
					["code-block"], //代码块
					//['video'] //视频
				],
				fileList_bg: [],
				dialogImageUrl_bg: "",
				dialogVisible_bg: false,

				fileList: [],
				dialogImageUrl: "",
				dialogVisible: false,
				myHeaders: {
					"access-token": this.$store.state.token, //这里重新定义了请求头
					Authorization: this.$store.state.token,
					"user-id": this.$store.state.user_id,
				},

				valueTime: [],
				id: "", //奖品id

				// 奖品类型弹出框
				dialogVisibleType: false,
				typePage: 1,
				typePagesize: 5,
				typeTotal: 0,
				typeList: [],
				selectTypeOk: {}, //已选择的
				searchShop: "",
				marketList: [],
				verifStatus: [{ //核销配置启用选择
						label: '启用',
						value: 1
					},
					{
						label: '关闭',
						value: 0
					}
				]
			};
		},
		mounted() {
			this.id = this.$route.query.id;
			if (this.id) {
				this.getActivityDetail();
			}
			//this.loadTypes();
			this.remoteMethod();
		},
		methods: {
			// 获取卖场列表
			remoteMethod() {
				this.$http.post("/api/root/Market/marketList").then((res) => {
					console.log(res, "卖场列表");
					if (res.code == 1) {
						this.marketList = res.data ? res.data : [];
					}
				});
			},
			// 选择卖场
			selectMarket() {

			},
			// 颜色选择器
			handleChangeColor(val) {
				console.log("输出颜色值", val); // 颜色 #6c8198
				this.form.back_color = val;
			},
			// 获取奖品详情
			getActivityDetail() {
				this.$http
					.post("/api/root/activity/prize/detail", {
						id: this.id
					})
					.then((res) => {
						console.log(res, "奖品详情");
						// if(res.code==1){
						this.form = {
							...res.data
						};
						this.form.status = res.data.status == 1 ? "1" : "0";
						this.form.is_verification = res.data.is_verification.toString();
						this.form.ispus = res.data.ispus.toString();
						this.form.type = res.data.type.toString();
						this.form.is_cate = res.data.is_cate.toString();
						let verif_conf_status = res.data.verif_conf_status;
						this.form.verif_conf_status = verif_conf_status; //核销配置
						if (res.data.is_verification==1 && res.data.is_cate == 1) {
							this.cates = res.data.cate_lst;
							let cateArr = [];
							res.data.cate_lst.map((item) => {
								cateArr.push(item.value);
							});
							this.cate_lst = cateArr;
						}
						if (res.data.start_at) {
							let startTime = this.$moment(res.data.start_at * 1000).format(
								"yyyy-MM-DD HH:mm:ss"
							);
							let endTime = this.$moment(res.data.end_at * 1000).format(
								"yyyy-MM-DD HH:mm:ss"
							);
							this.form.start_at = startTime;
							this.form.end_at = endTime;
							this.valueTime = [startTime, endTime];
						}

						// 主图
						if (res.data.img.length > 0) {
							res.data.img.map((item) => {
								this.fileList.push({
									url: item.path,
									id: item.id,
								});
							});
						}

						// }
					});
			},

			//切换选择的类型
			toSelectTypeFn() {
				this.form.rel_id = "";
				this.selectTypeOk = {};
			},
			// 点击选选择奖品类型
			selectType() {
				this.dialogVisibleType = true;
				this.typeList = [];
				if (this.form.type == "1") {
					this.getRootCouponList();
				} else if (this.form.type == "3") {
					this.getArticleList();
				} else if (this.form.type == "4") {
					this.getLiveList();
				}
			},
			// 对话框确定
			selectSubmit() {
				if (!this.form.rel_id) {
					this.$message.warning(
						this.form.type == "1" ?
						"请选择优惠券" :
						this.form.type == "3" ?
						"请选择促销文章" :
						this.form.type == "4" ?
						"请选择直播" :
						""
					);
					return;
				}
				this.selectTypeOk = this.typeList.find((item) => {
					if (this.form.type == "4") {
						//选择直播
						if (this.form.rel_id == item.qy_living_id) {
							return item;
						}
					} else {
						if (this.form.rel_id == item.id) {
							return item;
						}
					}
				});
				this.dialogVisibleType = false;
			},

			// 关闭对话框
			closeFn() {
				this.typeList = [];
				this.typePage = 1;
				this.typePagesize = 5;
			},

			// 搜索
			searchShopFn() {
				this.typePage = 1;
				this.typePagesize = 5;
				if (this.form.type == "1") {
					this.getRootCouponList();
				} else if (this.form.type == "3") {
					this.getArticleList();
				} else if (this.form.type == "4") {
					this.getLiveList();
				}
			},
			// 清除搜索
			clearShopFn() {
				if (this.searchShop == "") {
					this.typePage = 1;
					this.typePagesize = 5;
					if (this.form.type == "1") {
						this.getRootCouponList();
					} else if (this.form.type == "3") {
						this.getArticleList();
					} else if (this.form.type == "4") {
						this.getLiveList();
					}
				}
			},

			// 获取平台优惠券
			getRootCouponList() {
				let params = {
					is_platform: 1,
					sale_type: 3,
					page: this.typePage,
					pagesize: this.typePagesize,
				};
				this.$http
					.post("/api/root/CouponShop/getCouponLists", params)
					.then((res) => {
						console.log(res, "优惠券列表");
						if (res.code == 1) {
							this.typeList = res.data.lists ? res.data.lists : [];
							this.typeTotal = res.data.count;
						}
					});
			},
			// 获取促销文章
			getArticleList() {
				let params = {
					page: this.typePage,
					pagesize: this.typePagesize,
					keyword: this.searchShop,
					// group_id:1,
					// is_pub:1
				};
				this.$http.post("/api/root/Article/lists", params).then((res) => {
					console.log(res, "文章列表");
					if (res.code == 1) {
						this.typeList = res.data.articles ? res.data.articles : [];
						this.typeTotal = res.data.total;
					}
				});
			},
			// 获取直播列表
			getLiveList() {
				let params = {
					qy_user_id: [],
					status: [0, 1],
					cate_id: 0,
					id_open: 1,
					page: this.typePage,
					pagesize: this.typePagesize,
				};
				this.$http.post("/api/root/qywx/Living/getList", params).then((res) => {
					console.log(res, "直播列表");
					if (res.code == 1) {
						this.typeList = res.data.list ? res.data.list : [];
						this.typeTotal = res.data.count;
					}
				});
			},

			// 优惠券&促销文章&直播分页
			handleSizeChangeShop(val) {
				this.typePage = 1;
				this.typePagesize = val;
				if (this.form.type == "1") {
					this.getRootCouponList();
				} else if (this.form.type == "3") {
					this.getArticleList();
				} else if (this.form.type == "4") {
					this.getLiveList();
				}
			},
			handleCurrentChangeShop(val) {
				this.typePage = val;
				if (this.form.type == "1") {
					this.getRootCouponList();
				} else if (this.form.type == "3") {
					this.getArticleList();
				} else if (this.form.type == "4") {
					this.getLiveList();
				}
			},

			// 获取品类

			_query_cate(query) {
				if (this.form.market_id == '') {
					this.$message.warning('请先选择卖场')
					return
				}
				this.$http
					.post("/api/root/cate/choice", {
						keyword: query,
						market_id: this.form.market_id
					})
					.then((res) => {
						if (res.code == 1) {
							this.cates = res.data ? res.data : [];
						}
					});
			},

			// 选择时间
			selectTime() {
				console.log(this.valueTime, "----");
				if (this.valueTime) {
					this.form.start_at = this.$moment(this.valueTime[0]).format(
						"yyyy-MM-DD HH:mm:ss"
					);
					this.form.end_at = this.$moment(this.valueTime[1]).format(
						"yyyy-MM-DD HH:mm:ss"
					);
				}
				console.log(this.form, "000");
			},

			//   主图
			handleRemove(file, fileList) {
				this.fileList = fileList;
			},
			handlePictureCardPreview(file) {
				console.log("file", file);
				this.dialogImageUrl = file.url;
				this.dialogVisible = true;
			},
			handleAvatarSuccess(res, file, fileList) {
				console.log("fileList", fileList);
				this.fileList = fileList;
			},
			beforeAvatarUpload(file) {
				const isLt2M = file.size / 1024 / 1024 < 10;
				if (!isLt2M) {
					this.$message.error("上传奖品图片大小不能超过 10MB!");
				}
				return isLt2M;
			},

			confirmAdd(form) {
				console.log(this.cate_lst, "选择的品类");
				// return
				this.validateFormData(form);
				if (this.validate) {
					const _ths = this;
					// if(this.form.type_id.length > 0){
					//   this.form.type_id = this.form.type_id.pop();
					// }

					//   主图
					let imgArr = [];
					if (this.fileList.length > 0) {
						this.fileList.map((v) => {
							if (v.response) {
								imgArr.push(v.response.data.id);
							} else {
								imgArr.push(v.id);
							}
						});
					}
					this.form.img = imgArr.join(",");
					if (this.form.is_verification == 1 && this.form.is_cate != "0" && !this.cate_lst.length) {
						this.$message.warning("请添加品类限制");
						return;
					}
					if (this.form.type == 4 && !this.form.rel_id) {
						this.$message.warning("请输入直播ID");
						return;
					}
					if (this.form.verif_conf_status == 1) {
						if (this.form.verif_conf_data.lucky_count == '' || this.form.verif_conf_data.lucky_count == undefined) {
							this.$message.warning("请输入赠送抽奖次数");
							return;
						}
						let writeData = {
							lucky_count: this.form.verif_conf_data.lucky_count
						};
						this.form.verif_conf_data = JSON.stringify(writeData);
					}
					this.form.cate_lst =
						this.form.is_cate == "0" ? 0 : this.cate_lst.join(",");

					let url = this.id ?
						"/api/root/activity/prize/edit" :
						"/api/root/activity/prize/add";
					this.$http.post(url, {
						...this.form
					}).then((rest) => {
						if (rest.code == 1) {
							this.$message.success(this.id ? "修改成功" : "添加成功");
							setTimeout(function() {
								_ths.$router.back(1);
							}, 800);
						} else {
							this.form = {
								...this.form,
							};
							this.$message.error(rest.msg);
						}
					});
				}
			},
			cancel() {
				this.$router.back(1);
			},

			/**
			 * 验证表单数据
			 * @param form
			 */
			validateFormData(form) {
				this.$refs[form].validate((valid) => {
					if (!valid) {
						this.$message({
							message: "表单数据未填写完整,操作失败！",
							type: "warning",
						});
						return false;
					}
					this.validate = true;
					return true;
				});
			},
			//富文本上传图片
			handleImageAdded(file, Editor, cursorLocation, resetUploader) {
				var formData = new FormData();
				let isLtSize = file.size / 1024 / 1024 < 10;
				if (!isLtSize) {
					this.$message.warning("上传文件不能超过 10MB!");
					return;
				}
				this.editorLoading = true;
				formData.append("file", file);
				this.$http
					.post("/api/admin/base/uploadfile", formData)
					.then((result) => {
						if (result.msg !== "ok" || !result.data) {
							this.$message.error(result.msg);
							this.editorLoading = false;
							resetUploader();
							return false;
						}
						// 你上传路径返回的url
						let url = result.data.url;
						if (file.type === "video/mp4") {
							Editor.insertEmbed(cursorLocation, "video", url); //视频
						} else if (file.type === "audio/mpeg") {
							Editor.insertEmbed(cursorLocation, "video", url); //音频
						} else {
							Editor.insertEmbed(cursorLocation, "image", url);
						}
						resetUploader();
						this.editorLoading = false;
					})
					.catch((err) => {
						this.editorLoading = false;
					});
			},
			//   loadTypes() {
			//     var _ths = this;
			//     this.$http.post('/api/root/article/articleTypes', {})
			//       .then((rest) => {
			//         if (rest.data.length > 0) {
			//           _ths.types = rest.data;
			//         }
			//       })
			//   },
			handleParentType(value) {
				this.form.pid = value;
				if (this.$refs.organizerUnit) {
					this.$refs.organizerUnit.dropDownVisible = false;
				}
			},
		},
	};
</script>
<style lang="less" scoped>
	@import "index.less";
</style>
